//% color="#9932CC" iconWidth=50 iconHeisvght=40
namespace Csv{

    //% block="初始化CSV模块" blockType="command"
    export function Csv_init(parameter: any, block: any) {
        Generator.addImport(`import csv`)
        
    }
    //% block="以追加模式打开CSV文件[FILE]并返回[OBJECT]" blockType="command"
    //% FILE.shadow="string" FILE.defl="data.csv"
    //% OBJECT.shadow="normal" OBJECT.defl="csvfile"

    export function Csv_initopen(parameter: any, block: any) {
        let file=parameter.FILE.code;
        let obj=parameter.OBJECT.code; 
                
        Generator.addCode(`${obj} = open(${file}, 'a', newline='')`) 
    }
    //% block="判断CSV文件[CSV]是否存在?" blockType="boolean"
    //% CSV.shadow="string" CSV.defl="data.csv"
    export function Csv_initopen1(parameter: any, block: any) {
     
        let csv=parameter.CSV.code; 
        Generator.addImport(`import os.path`)        
        Generator.addCode(`not os.path.isfile(${csv})`) 
    }

     //% block="---"
     export function noteSep1() {}

    //% block="对象名[OBJECT] 设置以字典方式写入 设置表头[DICT]" blockType="command"
    //% OBJECT.shadow="normal" OBJECT.defl="csvfile"
    //% DICT.shadow="list" DICT.defl="'index'"
    export function Csv_inittype(parameter: any, block: any) {
        let obj=parameter.OBJECT.code; 
        let dtic=parameter.DICT.code; 
                 
        Generator.addCode(`writer = csv.DictWriter(${obj}, fieldnames=${dtic})` 

}

    //% block="向CSV文件增加字典数据[DT]" blockType="command"
    //% DT.shadow="dictionary" DT.defl="'index':'序号'"
    export function Csv_inittype2(parameter: any, block: any) {

        let dt=parameter.DT.code;                 
        Generator.addCode(`writer.writerow(${dt})`)
    }
    //% block="---"
    export function noteSep2() {}

    //% block="对象名[OBJECT] 设置以列表方式写入" blockType="command"
    //% OBJECT.shadow="normal" OBJECT.defl="csvfile"
    export function Csv_inittype_list(parameter: any, block: any) {
        let obj=parameter.OBJECT.code; 
                 
        Generator.addCode(`writer = csv.writer(${obj})` 

}

    //% block="向CSV文件增加列表数据[LS]" blockType="command"
    //% LS.shadow="list" LS.defl='"1","2"' 
    export function Csv_inittype2_list(parameter: any, block: any) {

        let LS=parameter.LS.code;                 
        Generator.addCode(`writer.writerow(${LS})`)
    }
   
 //% block="---"
    export function noteSep3() {}
    
    //% block="[OBJECT]关闭文件" blockType="command"
    //% OBJECT.shadow="normal" OBJECT.defl="csvfile"
    export function Csv_inittype1(parameter: any, block: any) {
        let obj=parameter.OBJECT.code; 
              
        Generator.addCode(`${obj}.close()`)
    }
  
}


